package org.jpro.modules.system.service.impl;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.jpro.modules.system.dao.RolePermissionRepository;
import org.jpro.modules.system.entity.Permission;
import org.jpro.modules.system.entity.Role;
import org.jpro.modules.system.entity.RolePermission;
import org.jpro.modules.system.realm.AuthorizingRealm;
import org.jpro.modules.system.service.IRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <P>功能描述 : 角色权限service实现 </P>
 * <P>File name : RolePermissionServiceImpl </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/4 上午12:02</P>
 */
@Service
@Transactional(readOnly = true)
public class RolePermissionServiceImpl implements IRolePermissionService {

    @Autowired
    private RolePermissionRepository rolePermissionRepository;

    @Override
    public List<Integer> getPermissionIds(Integer id) {
        return rolePermissionRepository.findPermissionIds(id);
    }

    @Override
    public void clearUserPermCache(PrincipalCollection pc) {
        RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        AuthorizingRealm userRealm = (AuthorizingRealm) securityManager.getRealms().iterator().next();
        userRealm.clearCachedAuthorizationInfo(pc);
    }

    @Override
    @Transactional
    public void updateRolePermission(Integer id, List<Integer> oldList, List<Integer> newList) {
        // 是否删除
        for (int i = 0, j = oldList.size(); i < j; i++) {
            if (!newList.contains(oldList.get(i))) {
                rolePermissionRepository.deleteRP(id, oldList.get(i));
            }
        }

        // 是否添加
        for (int i = 0, j = newList.size(); i < j; i++) {
            if (!oldList.contains(newList.get(i))) {
                rolePermissionRepository.save(getRolePermission(id, newList.get(i)));
            }
        }
    }

    /**
     * 构造角色权限对象
     * @param roleId
     * @param permissionId
     * @return RolePermission
     */
    private RolePermission getRolePermission(Integer roleId, Integer permissionId) {
        RolePermission rp = new RolePermission();
        rp.setRole(new Role(roleId));
        rp.setPermission(new Permission(permissionId));
        return rp;
    }
}
